<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>负载信息</title>
  <style>
    .container {
      width: 100%;
      word-wrap: break-word;
      box-sizing: border-box;
    }

    .bold, [bold] {
      font-weight: bold;
    }

    p,div {
      color: #424242;
      line-height: 120%;
    }
    
    .row, [row] {
      box-sizing: border-box;
      flex: 0 1 auto;
      display: flex;
      flex-flow: row wrap;
    }

    .row-nowrap, [row-nowrap] {
      flex-flow: row nowrap;
    }

    .row-space, [row-space] {
      justify-content: space-around;
    }

    .cell, [cell] {
      padding-left: 0.5rem;
      padding-right: 0.5rem;
      flex: 1;
    }

  </style>
</head>
<body>
  <div class="container" style="padding:0.5rem;">
    <div style="text-align: center;line-height: 168%;font-size: 128%;">进程负载信息</div>
    <div style="margin-top:1rem;padding:0.5rem;" id="main">
    </div>
  </div>
  <script>

    function renderLoadInfo(ld) {
      let d = document.querySelector('#main')

      let text = ''

      let http2_tag = ''
      if (ld.http2) {
        http2_tag = `<span bold style="font-size:85%;background:#f1f2f3;padding:0.15rem;border-radius:0.12rem;">http2</span>`
      }
      text += `<p>
          <span bold>主进程PID: ${ld.masterPid}</span>
          &nbsp;
          <span bold>Listen: ${ld.https ? 'https' : 'http'}://${ld.listen}</span>
          &nbsp;
          ${http2_tag}
        </p>`

      let cpu = ld.CPULoadavg
      text += `<p>CPU平均负载：${cpu['1m']}(1分钟) ${cpu['5m']}(5分钟) ${cpu['15m']}(15分钟)</p>`

      text += `<p style="border-radius:0.2rem;background:#efefef;padding:0.2rem;text-align:center;">Workers</p>`

      text += `<div row>
        <div cell bold>PID</div>
        <div cell bold>CPU</div>
        <div cell bold>RSS内存</div>
        <div cell bold>HEAP内存</div>
        <div cell bold>HEAP已使用</div>
        <div cell bold>连接</div>
      </div>`
      let bgcolor = '#ffffff'

      for (let w of ld.workers) {
        text += `<div row style="background:${bgcolor};margin-top:0.2rem;">
          <div cell>${w.pid}</div>
          <div cell>${w.cpu}</div>
          <div cell>${w.mem.rss}M</div>
          <div cell>${w.mem.heap}M</div>
          <div cell>${w.mem.heapused}M</div>
          <div cell>${w.conn}</div>
        </div>`
        if (bgcolor === '#ffffff') {
          bgcolor = '#f1f2f3'
        } else {
          bgcolor = '#ffffff'
        }
      }

      d.innerHTML = text
    }

    let es = new EventSource('/sys/loadinfo?key=2022.web.ok')

    es.onerror = err => {
      //有可能是定时关闭连接，并非所有的都是error
      console.error(err)
    }

    es.addEventListener('message', e => {
      console.log(e.data)
    })

    es.addEventListener('loadinfo', e => {
      let loadinfo = JSON.parse(e.data)
      renderLoadInfo(loadinfo)
    })


  </script>
</body>
</html>